package books.storage.service;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jws.WebService;

import books.storage.dto.AuthorDto;
import books.storage.eao.AuthorManagerEao;
import books.storage.eao.BooksStorageEao;
import books.storage.entity.AuthorEntity;
import books.storage.exception.EntityNotFoundException;
import books.storage.util.Conversion;

/**
 * Session Bean implementation class AuthorManagerBean
 */
@Stateless
@LocalBean
@WebService
public class AuthorsManagerBean implements IAuthorsManagerBean {

	@EJB
	BooksStorageEao eao;
	@EJB
	AuthorManagerEao aeao;
	@EJB
	Conversion conv;

	/**
	 * Default constructor.
	 */
	public AuthorsManagerBean() {
	}

	public AuthorsManagerBean(BooksStorageEao eao, AuthorManagerEao aeao,
			Conversion conv) {
		this.eao = eao;
		this.aeao = aeao;
		this.conv = conv;
	}

	/*
	 * INSERT METHODS
	 */
	public AuthorDto addNewAuthor(AuthorDto _author)
			throws EntityNotFoundException {
		AuthorEntity author = this.conv.fromAuthorDto(_author);
		this.eao.insertEntity(author);
		return this.conv.fromAuthorEntity(author);
	}

	/*
	 * DELETE METHODS
	 */
	public void deleteAuthor(AuthorDto _author) throws EntityNotFoundException {
		this.eao.deleteEntity(this.conv.fromAuthorDto(_author));
	}

	/*
	 * UPDATE METHODS
	 */
	public AuthorDto updateAuthor(AuthorDto _author)
			throws EntityNotFoundException {
		AuthorEntity author = this.conv.fromAuthorDto(_author);
		this.eao.updateEntity(author);
		return this.conv.fromAuthorEntity(author);
	}

	/*
	 * SEARCH METHODS
	 */
	public AuthorDto findAuthorDto(Integer _id) throws EntityNotFoundException {
		return this.conv.fromAuthorEntity(this.eao.findOrFail(
				AuthorEntity.class, _id));
	}

	/*
	 * SEARCH METHODS
	 */

	public AuthorDto authorByName(String authorName) {
		AuthorDto authorDto = conv.fromAuthorEntity(aeao.authorByName(authorName));
		return authorDto;
	}

	public List<AuthorDto> authorByBook(String bookTitle) {
		List<AuthorDto> result = new ArrayList<AuthorDto>();
		List<AuthorEntity> authorsByBook = aeao.authorByBook(bookTitle);
		for (AuthorEntity author : authorsByBook) {
			AuthorDto authorDto = conv.fromAuthorEntity(author);
			result.add(authorDto);
		}
		return result;
	}

	public List<AuthorDto> findAllAuthors() {
		List<AuthorDto> authors = new ArrayList<>();
		for (AuthorEntity author : this.eao.getAllEntities(AuthorEntity.class)) {
			authors.add(this.conv.fromAuthorEntity(author));
		}
		return authors;
	}
}
